import axios from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL: 'http://117.72.106.234:8080/api',
});

// 请求拦截器，为请求添加token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const networkService = {
  // 获取用户关联的局域网列表
  getUserNetworks: (filter = 'managed') => {
    return api.get(`/network/list?filter=${filter}`);
  },

  // 搜索/筛选局域网
  searchNetworks: (params) => {
    return api.get('/network/search', { params });
  },

  // 获取特定局域网的详细信息
  getNetworkDetail: (networkId) => {
    return api.get(`/network/${networkId}`);
  },

  // 创建局域网
  createNetwork: (networkData) => {
    return api.post('/network/create', networkData);
  },

  // 更新局域网信息
  updateNetwork: (networkId, updateData) => {
    return api.put(`/network/${networkId}`, updateData);
  },

  // 获取局域网规则配置
  getNetworkRules: (networkId) => {
    return api.get(`/network/${networkId}/rules`);
  },

  // 更新网络规则
  updateNetworkRules: (networkId, rulesData) => {
    return api.put(`/network/${networkId}/rules`, rulesData);
  },

  // 加入局域网
  joinNetwork: (networkId) => {
    return api.post(`/network_management/${networkId}/join`);
  },

  // 退出局域网
  leaveNetwork: (networkId) => {
    return api.post(`/network_management/${networkId}/leave`);
  },

  // 获取局域网成员列表
  getNetworkMembers: (networkId) => {
    return api.get(`/network_management/${networkId}/members`);
  },

  // 更改成员角色
  updateMemberRole: (networkId, userId, role) => {
    return api.put(`/network_management/${networkId}/member/${userId}/role`, { role });
  },

  // 移除成员
  removeMember: (networkId, userId, banDuration = 0) => {
    return api.post(`/network_management/${networkId}/member/${userId}/remove?banDuration=${banDuration}`);
  },

  // 获取用户在网络中的角色
  getUserNetworkRole: (networkId) => {
    return api.get(`/network_management/${networkId}/role`);
  }
};

export default networkService;